
#include "main.h"
#include "assitant.h"
#include "jcs_builtin.h"

#pragma region DHT11

int JCSensor_DHT11::setup(String &param)
{
    out_("setup sensor DHT11 in pin:");
    outs(param);
    int pin; //, vcc_pin = -1;
    if (param[0] != '-')
    {
        var s = param; // a backup
        var c = param[1];
        if (c == '1') // D1 as input, so D0 is GND
        {
            xouts("D0 is used");
            return -__LINE__;
        }
        s.setCharAt(1, c - 1); // ->GND
        pin = cast_to_pin(s);
        if (pin < 0)
        {
            return -__LINE__;
        }
        pinMode(pin, OUTPUT);
        digitalWrite(pin, 0);
        out_(s);
        outs(" -> GND");
        s.setCharAt(1, c + 1); // ->VCC
        pin = cast_to_pin(s);
        if (pin < 0)
        {
            return -__LINE__;
        }
        pinMode(pin, OUTPUT);
        digitalWrite(pin, 1);
        out_(s);
        outs(" -> VCC");
        pin = cast_to_pin(param);
    }
    else
    {
        var s = param.substring(1);
        pin = cast_to_pin(s);
    }
    if (pin < 0)
    {
        return -__LINE__;
    }
    dht = new DHTesp();
    if (dht == NULL)
    {
        return -__LINE__;
    }
    dht->setup(pin, DHTesp::DHT11);
    return 0;
}

String JCSensor_DHT11::read()
{
    TempAndHumidity d = dht->getTempAndHumidity();
    int error = dht->getStatus();
    if (error)
    {
        String empty;
        return empty;
    }
    sprintf(tx_back, "\"temperature\":%.1f,\"humidity\":%.0f", d.temperature, d.humidity);
    String res(tx_back);
    return res;
}

JCSensor_DHT11::~JCSensor_DHT11()
{
    if (dht)
        delete dht;
}
#pragma endregion

#pragma region ADC

int JCSensor_ADC::setup(String &param)
{
    if (param.isEmpty())
    {
        return -__LINE__;
    }
    else
    {
        this->tag = param;
    }
    xout_("set up an adc:");
    xouts(tag);
    return 0;
}
String JCSensor_ADC::read()
{
    int val = analogRead(A0);
    sprintf(tx_back, "\"%s\":%d", tag.c_str(), val);
    String res(tx_back);
    return res;
}
String JCSensor_NADC::read()
{
    int val = 1024 - analogRead(A0);
    sprintf(tx_back, "\"%s\":%d", tag.c_str(), val);
    String res(tx_back);
    return res;
}

#pragma endregion
